package com.message.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseDaoImpl2 extends HibernateDaoSupport implements BaseDao {

	@Override
	public Object getObject(Class<?> clazz, int id) {
		return super.getHibernateTemplate().get(clazz, id);
	}

	@Override
	public int Update(Object obj, int opt) {
		switch (opt) {
		case 1:
			super.getHibernateTemplate().save(obj);
			break;
		case 2:
			super.getHibernateTemplate().delete(obj);
			break;
		case 3:
			super.getHibernateTemplate().update(obj);
			break;
		default:
			break;
		}
		return 1;
	}

	@Override
	public List<?> query(String hql, Object params) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<?> query(final String hql, final Object params, final int pageNow, final int pageSize) {
		return super.getHibernateTemplate().executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if (params != null) {
					query.setProperties(params);
				}
				if (pageNow != 0) {
					query.setFirstResult(pageSize * (pageNow - 1));
					query.setMaxResults(pageSize);
				}
				return query.list();
			}
		});
	}
}
